<?php
@list($level, $gold, $cash, $sizeX, $sizeY, $firstname, $locale) = explode(';', @file_get_contents(F('playerinfo.txt')));

$map_image = AllForTrees_Path . "data/" . $vWorldtype . $userId . "_Map.png";

$vAllTrees = AFT_MakeTreeDB('');	
list(, , , $sizeX, $sizeY) = explode(';', file_get_contents(F('playerinfo.txt')));

$vSettings = AFT_load('settings');
$vSections = AFT_load('sections');

AllForTrees_Create_Map();

if ($_GET['reloadMap']) exit;

?>
<script src="jquery.imgareaselect.js"></script>
<script>
var mouseDown = false;
var farmSizeX = <?=$sizeX ?>;
var farmSizeY = <?=$sizeY ?>;
var imgH;
var imgW;
var offset;
var cPosX;
var cPosY;
var cTarget;
var x1;
var y2;
var x2;
var y2;
$(document).ready(function(){

/*	$('img#map').imgAreaSelect({
		handles: true,
	});
*/
/*	$('img#map').click(function(e){
		point_it(e);
	});
	*/
	$('button.pick').click(function(e){
		$(cTarget).removeClass("picked");
		cTarget=$(e.delegateTarget).next('table');
		$(cTarget).addClass("picked");
	});
	$('#div_map').mousemove(function(e){ mouseMove(e); 
	}).mousedown(function(e){
		mouseDown = true;
		$('#selRect').css('left',cPosX);
		$('#selRect').css('top',cPosY);
	});
	$(document).mouseup(function(e){
		mouseDown = false;
		if (cTarget) {
			$(cTarget).find('[name*="x1"]').val(x1).change();
			$(cTarget).find('[name*="y1"]').val(y1).change();
			$(cTarget).find('[name*="x2"]').val(x2).change();
			$(cTarget).find('[name*="y2"]').val(y2).change();
			$(cTarget).removeClass("picked");
			cTarget = null;
		};
	});
	$('input[name*="x1"], input[name*="x2"], input[name*="y1"], input[name*="y2"]').on("change", function(ev) {
		var table = $(this).closest('table');
		var x1 = $(table).find('input[name*="x1"]').val();
		var x2 = $(table).find('input[name*="x2"]').val();
		var y1 = $(table).find('input[name*="y1"]').val();
		var y2 = $(table).find('input[name*="y2"]').val();
		$(table).closest('td').prev().html((x2-x1)*(y2-y1));
	});
});
function mouseMove(event) {
	var offset = $(event.delegateTarget).offset();
	var off_x = event.offsetX?(event.offsetX):event.pageX-offset.left;
	var off_y = event.offsetY?(event.offsetY):event.pageY-offset.top;
//console.log(offset,event.offsetX,event.offsetY,event.pageX,event.pageY,off_x,off_y);
	var pos_x = Math.round((off_x * farmSizeX) / $("img#map").width());
	var pos_y = Math.round((($("img#map").height() - off_y) * farmSizeY) / $("img#map").height());
	$('#current_xpos').html(pos_x + "(" + off_x + ")");
	$('#current_ypos').html(pos_y + "(" + off_y + ")");
	$('#vbar').css('left',off_x-1);
	$('#hbar').css('top',off_y-1);
	cPosX = off_x;
	cPosY = off_y;
	if (mouseDown) {
		$('#selRect').css('width',cPosX-$('#selRect').position().left-2);
		$('#selRect').css('height',cPosY-$('#selRect').position().top-2);
		x2 = pos_x;
		y1 = pos_y;
		$('#selRect').html('<span>'+(x2-x1)+"x"+(y2-y1)+" ("+((x2-x1)*(y2-y1))+")</span>");
	} else {
		x1 = pos_x;
		y2 = pos_y;
	}
}
function removeSec(el,id) {
	$(el).closest('tr').fadeOut(500).remove();
	fAction("saveConf&name=section-"+id+"-remove&val=1");
}
function reloadMap() {
	var w = $('img#map').css('width');
	var h = $('img#map').css('height');
	$('img#map').attr('src','');
	$('img#map').css('width',w).css('height',h);
	$.get("?reloadMap=1", function() {
		$('img#map').attr('src','<?=$map_image?>');
	});
}
</script>
<link rel="stylesheet" href="imgareaselect-default.css">
<style>
	div.line {
		position:absolute;
		border:none;
		background-color:white;
		z-index:100;
	}
	#div_map { position:relative; }
	div#selRect { border:1px solid yellow; background:none; position:absolute; color:black; font-size:9px;background:url();}
	div#selRect span { background-color:yellow; }
	.picked td {background-color:yellow;}
	input[name="x1"], input[name="x2"], input[name="y1"], input[name="y2"] { width:25px;}
</style>

<?php

if ($_POST['faction2'] == 'add_section'){
	$vSections = array();
	$vSections = AFT_load('sections');
	if (count($vSections) > 0) {
		$vNum=$vSections[count($vSections) - 1]['id'] + 1;
	} else $vNum=1;	
	
	if ($_POST['x2']>$_POST['x1'] ){
		$vtx=$_POST['x2'];
		$vbx=$_POST['x1'];
	} else {
		$vbx=$_POST['x2'];
		$vtx=$_POST['x1'];
	}
	if ($_POST['y2']>$_POST['y1'] ){
		$vty=$_POST['y2'];
		$vby=$_POST['y1'];
	} else {
		$vby=$_POST['y2'];
		$vty=$_POST['y1'];
	}
	if ($vtx>$sizeX-1) $vtx=$sizeX-1;
	if ($vty>$sizeY-1) $vty=$sizeY-1;
	if ($vbx<0) $vbx=0;
	if ($vby<0) $vby=0;
	$vsec=array();
	if ($_POST['multiple']=='ok') {
		$w=$_POST['w'];
		$h=$_POST['h'];
		$sx=$_POST['sx'];
		$sy=$_POST['sy'];
		$valanlar=array();
		$valanlar=crmultiple($vbx,$vtx,$vby,$vty,$w,$h,$sx,$sy,$vNum,$_POST['order']);
		foreach ($valanlar as $valan) {
			$vSections[]=$valan;
		}
	} else {
		$vsec['id']   = $vNum;
		$vsec['order'] = $_POST['order'];
		$vsec['x2'] = $vtx;
		$vsec['y2'] = $vty;
		$vsec['x1'] = $vbx;
		$vsec['y1'] = $vby;		
		$vSections[]=$vsec;
	}
	AFT_save($vSections, 'sections');
}

if ($_POST['faction2'] == 'sec_settings'){

	$vSettings = array();
	$vSettings = AFT_load('settings');
	if ($_POST['seed_x1']<$_POST['seed_x2'] ){
		$vSettings['seed_x1']=$_POST['seed_x1'];
		$vSettings['seed_x2']=$_POST['seed_x2'];
	} else {
		$vSettings['seed_x1']=$_POST['seed_x2'];
		$vSettings['seed_x2']=$_POST['seed_x1'];
	}
	if ($_POST['seed_y1']<$_POST['seed_y2'] ){
		$vSettings['seed_y1']=$_POST['seed_y1'];
		$vSettings['seed_y2']=$_POST['seed_y2'];
	} else {
		$vSettings['seed_y1']=$_POST['seed_y2'];
		$vSettings['seed_y2']=$_POST['seed_y1'];
	}
	AFT_save($vSettings, 'settings');
	$vAllTrees = array();
	$vAllTrees = AFT_load('alltrees');

	$vSections = array();
	$vids=$_POST['sid'];
	$vorder=$_POST['order'];
	$vx1=$_POST['x1'];
	$vy1=$_POST['y1'];
	$vx2=$_POST['x2'];
	$vy2=$_POST['y2'];

	$vcont =$_POST['content'];
	$vsrem =$_POST['sec_remove'];


	if (!is_array($vids)) {
		if ($vsrem==$vids) {
			for ($u=0; $u< count($vAllTrees); $u++) {
				if ($vAllTrees[$u]['movetosec']==$vsrem)
					$vAllTrees[$u]['movetosec']=0;
				$vAllTrees[$u]['action']='';
			}
			AFT_save($vAllTrees, 'alltrees');
			AFT_save($vSections, 'sections');
		} else {
			$vsec=array();
			$vsec['id']=$vids;
			$vsec['order'] = $vorder;
			if ($vx2>$vx1){
				$vsec['x2'] = $vx2;
				$vsec['x1'] = $vx1;
			} else {
				$vsec['x2'] = $vx1;
				$vsec['x1'] = $vx2;
			}
			if ($vy2>$vy1){
				$vsec['y2'] = $vy2;
				$vsec['y1'] = $vy1;
			} else {
				$vsec['y2'] = $vy1;
				$vsec['y1'] = $vy2;
			}
			if ($vx2>$sizeX-1) $vx2=$sizeX-1;
			if ($vy2>$sizeY-1) $vy2=$sizeY-1;				
			if ($vx1<0) $vx1=0;
			if ($vy1<0) $vy1=0;				
			$vSections[]=$vsec;
			AFT_save($vSections, 'sections');
		}
	} else {
		for ($i=0; ($i<count($vids)); $i++) {
			$vsec=array();
			$vsec['id']=$vids[$i];
			$vsec['order'] = $vorder[$i];
			if ($vx2[$i]>$vx1[$i]){
				$vsec['x2'] = $vx2[$i];
				$vsec['x1'] = $vx1[$i];
			} else {
				$vsec['x2'] = $vx1[$i];
				$vsec['x1'] = $vx2[$i];
			}
			if ($vy2[$i]>$vy1[$i]){
				$vsec['y2'] = $vy2[$i];
				$vsec['y1'] = $vy1[$i];
			} else {
				$vsec['y2'] = $vy1[$i];
				$vsec['y1'] = $vy2[$i];
		}
		if ($vsec['x2']>$sizeX-1) $vsec['x2']=$sizeX-1;
		if ($vsec['y2']>$sizeY-1) $vsec['y2']=$sizeY-1;
		if ($vsec['x1']<0) $vsec['x1']=0;
		if ($vsec['y1']<0) $vsec['y1']=0;
	
		$vrem=false;
		for ($j=0; ($j<count($vsrem)); $j++) {
			if ($vsrem[$j]==$vids[$i]) {
				$vrem=true;
				for ($u=0; $u< count($vAllTrees); $u++) {
					if ($vAllTrees[$u]['movetosec']==$vsrem[$j]) {
						$vAllTrees[$u]['movetosec']=0;
						$vAllTrees[$u]['action']='';
					}
				}
			}
		}
		if ($vrem==false)
			$vSections[]=$vsec;
		}
		AFT_save($vSections, 'sections');	
		AFT_save($vAllTrees, 'alltrees');	
	}
} 
	


?>

<table class="grid">
	<tbody>
		<tr>
			<td style="text-align: center; vertical-align: top; " rowspan="3">
				<div id="div_map">
					<img id="map" src="<?=$map_image?>" style="z-index:1;">
					<div id="hbar" class="line" style="height:1px;width:100%;left:0px;"></div>
					<div id="vbar" class="line" style="width:1px;height:100%;top:0px;"></div>
					<div id="selRect"></div>
				</div>						
				<div style="position:absolute">x=<span id="current_xpos"></span>, y=<span id="current_ypos"></span></div>
			</td>
			<td style="width: 300px;text-align:left;font-family:Roboto;text-align:center;">
				<button onclick="reloadMap();return false;">Reload Map</button>
			</td>
		</tr>
		<tr>
			<td>
				<div style="text-align:right">
				Move unmastered trees to <select name="settings-unmasteredSection" class="saveConf">
<?php
				echo '<option value="0">[don\'t move]</option>';
				foreach ($vSections as $sec) {
					echo "<option value=\"{$sec['id']}\"".($vSettings['unmasteredSection'] == $sec['id']?" selected":"").">{$sec['name']} [{$sec['id']}]</option>";
				}
?>				
				</select>
				<br>
				Move mastered trees to <select name="settings-masteredSection" class="saveConf">
<?php
				echo '<option value="0">[don\'t move]</option>';
				foreach ($vSections as $sec) {
					echo "<option value=\"{$sec['id']}\"".($vSettings['masteredSection'] == $sec['id']?" selected":"").">{$sec['name']} [{$sec['id']}]</option>";
				}
?>
				</select>
				<br><br>
				(only for trees that are not bound to any section yet)
			</td>
		</tr>
		<tr>
			<td>
				<form action="<?=AllForTrees_URL?>" method="post" name="sections"><center>
					<button class="pick">pick</button>
					<table class="blind">
						<tr>
							<td style="vertical-align:middle;">Left:&nbsp;<input maxlength="3" name="x1" size="3" type="text" value="<?=$vbx?>"></td>
							<td>
								Top:&nbsp;<input maxlength="3" name="y2" size="3" type="text" value="<?=$vty?>"><br>
								Bottom:&nbsp;<input maxlength="3" name="y1" size="3" type="text" value="<?=$vby?>">
							</td>
							<td style="vertical-align:middle;">Right:&nbsp;<input maxlength="3" name="x2" size="3" type="text" value="<?=$vtx?>"></td>
						</tr>
					
						<tr>
							<td style="text-align: right;">Order</td>
							<td colspan="2">
								<select name="order" size="1">
									<option value="r0x">Top 0&rarr;X</option>
									<option value="r0y">Top 0&rarr;Y</option>
									<option value="rx0">Top X&rarr;0</option>
									<option value="ry0">Top Y&rarr;0</option>
									<option value="0x">0&rarr;X</option>
									<option value="0y">0&rarr;Y</option>
									<option value="x0">X&rarr;0</option>
									<option value="y0">Y&rarr;0</option>
									<option value="random" selected>Random</option>
								</select>
							</td>
						</tr>
						<tr>
							<td style="text-align: right;">Create Multiple</td>
							<td colspan="2"><input name="multiple" type="checkbox" value="ok" />
						</tr>
						<tr>
							<td style="text-align: right;">Width/Height</td>
							<td colspan="2"><input maxlength="3" name="w" size="3" type="text" value="1" /><input maxlength="3" name="h" size="3" type="text" value="1" /></td>
						</tr>
						<tr>
							<td style="text-align: right;">Spaces X/Y</td>
							<td colspan="2"><input maxlength="3" name="sx" size="3" type="text" value="0" /><input maxlength="3" name="sy" size="3" type="text" value="0" /></td>
						</tr>
						<tr>
							<td style="text-align: right;" colspan="3">
								<input name="faction2" type="hidden" value="add_section" />
								<input name="save" type="submit" value="Add Section" />
							</td>
						</tr>
					</table>
				</form>
			</td>
		</tr>
	</tbody>
</table>				
			
<br>

<table class="grid">
	<caption>Sections</caption>
	<thead>
		<tr>
			<th>Id</th>
			<th>Name</th>
			<th>Size</th>
			<th>Geometry</th>
			<th>Order</th>
			<th>Content</th>
		</tr>
	</thead>
	<tbody>
<?php

// Seedling section
?>
	<tr>
		<td style="font-weight:bold;">&nbsp;</td>
		<td style="font-weight:bold;">Seeds</td>
		<td style=""><?=(($vSettings['seed_x2'] - $vSettings['seed_x1'] +1) * ($vSettings['seed_y2'] - $vSettings['seed_y1'] +1)) ?></td>
		<td style="">
			<button class="pick">pick</button>
			<table class="blind">
				<tr>
					<td rowspan="2">Left:&nbsp;<input maxlength="3" class="saveConf" name="settings-seed_x1" size="3" type="text" value="<?=$vSettings['seed_x1']?>"></td>
					<td>
						Top:&nbsp;<input maxlength="3" class="saveConf" name="settings-seed_y2" size="3" type="text" value="<?=$vSettings['seed_y2']?>"><br>
						Bottom:&nbsp;<input maxlength="3" class="saveConf" name="settings-seed_y1" size="3" type="text" value="<?=$vSettings['seed_y1']?>">
					</td>
					<td rowspan="2">Right:&nbsp;<input maxlength="3" class="saveConf" name="settings-seed_x2" size="3" type="text" value="<?=$vSettings['seed_x2']?>"></td>
				</tr>
			</table>
		</td>
		</td><td>
		<td>Seedlings</td>
	</tr>

<?php
// other sections

$vSections = array();
$vSections = AFT_load('sections');

foreach ($vSections as $vsec) {
	$vtx=$vsec['x2'];
	$vbx=$vsec['x1'];
	$vty=$vsec['y2'];
	$vby=$vsec['y1'];

	if ($vtx == 0 && $vbx == 0 && $vty == 0 && $vby == 0) continue;
?>	
	<tr>
		<td style="vertical-align: top;font-weight:bold;"><?=$vsec['id']?><input name="sid" type="hidden" value="<?=$vsec['id']?>" /></td>
		<td style="vertical-align: top;font-weight:bold;">
			<input name="section-<?=$vsec['id']?>-name" type="text" class="saveConf" value="<?=$vsec['name']?>" /><br>
			<button type="button" onclick="removeSec(this,'<?=$vsec['id']?>');return false;">Remove Section</button>
		</td>
		<td style="vertical-align: top;"><?=(($vtx - $vbx +1) * ($vty - $vby +1))?></td>

		<td style="vertical-align: top;">
			<button style="float:right" class="pick">pick</button>
			<table class="blind">
				<tr>
					<td rowspan="2">Left:&nbsp;<input class="saveConf" maxlength="3" name="section-<?=$vsec['id']?>-x1" size="3" type="text" value="<?=$vbx?>"></td>
					<td>
						Top:&nbsp;<input class="saveConf" maxlength="3" name="section-<?=$vsec['id']?>-y2" size="3" type="text" value="<?=$vty?>"><br>
						Bottom:&nbsp;<input class="saveConf" maxlength="3" name="section-<?=$vsec['id']?>-y1" size="3" type="text" value="<?=$vby?>">
					</td>
					<td rowspan="2">Right:&nbsp;<input class="saveConf" maxlength="3" name="section-<?=$vsec['id']?>-x2" size="3" type="text" value="<?=$vtx?>"></td>
				</tr>
			</table>
		</td>
		<td style="vertical-align:top;">
			<select name="section-<?=$vsec['id']?>-order" size="1" class="saveConf">
				<option value="r0x"<?=$vsec['order']=='r0x'?' selected':''?>>Top 0&rarr;X</option>
				<option value="r0y"<?=$vsec['order']=='r0y'?' selected':''?>>Top 0&rarr;Y</option>
				<option value="rx0"<?=$vsec['order']=='rx0'?' selected':''?>>Top X&rarr;0</option>
				<option value="ry0"<?=$vsec['order']=='ry0'?' selected':''?>>Top Y&rarr;0</option>
				<option value="0x" <?=$vsec['order']=='0x'?' selected':''?>>0&rarr;X</option>
				<option value="0y" <?=$vsec['order']=='0y'?' selected':''?>>0&rarr;Y</option>
				<option value="x0" <?=$vsec['order']=='x0'?' selected':''?>>X&rarr;0</option>
				<option value="y0" <?=$vsec['order']=='y0'?' selected':''?>>Y&rarr;0</option>
				<option value="random"<?=$vsec['order']=='random'?' selected':''?>>Random</option>
			</select>
		</td>

		<td style="vertical-align: middle;">
		<?php
		if ($vSettings['unmasteredSection'] == $vsec['id']) echo "Unmastered trees<br>";
		if ($vSettings['masteredSection'] == $vsec['id']) echo "Mastered trees<br>";
		?>
			<table border=0>

<?php
		foreach ($vAllTrees as $vATr) {
			if ($vATr['movetosec'] == $vsec['id']) {
				echo '<tr>';
				echo AFT_tr($vATr,array('icon','nameF','mastery'));
?>
		<td>Section: <select name="actn" size="1" onchange="fAction('faction=movetosec&code=<?=$vATr['code']?>&val=',this.value)" >
<?php
				echo '<option value="0">&nbsp;</option>';
				foreach ($vSections as $vsec2) {
					$vslct='';
					if ($vATr['movetosec']==$vsec2['id']) $vslct=' selected';
					echo '<option value="'.$vsec2['id'].'"'.$vslct.">{$vsec2['name']} [{$vsec2['id']}]</option>";
				}
				echo '</select></td>';
				echo '</tr>';
			}
		}		
		echo '</table></td></tr>';
	}
?>	
	</tbody>
</table>
